<template>
	<view class="food-store-page">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<text class="title">美食商家</text>
			<!-- 原生搜索框 -->
			<view class="search-box">
				<uni-icons type="search" size="16" color="#999" class="search-icon"></uni-icons>
				<input type="text" placeholder="搜索美食/商家名称" v-model="searchKey" @input="handleSearch"
					@confirm="handleSearchConfirm" class="search-input" />
				<!-- 清空按钮 -->
				<uni-icons v-if="searchKey" type="clear" size="16" color="#999" class="clear-icon"
					@click="clearSearch"></uni-icons>
			</view>
		</view>

		<!-- 筛选栏（仅保留触发按钮，删除弹窗） -->
		<view class="filter-bar">
			<view class="filter-item">
				<text class="filter-text">全部状态</text>
				<uni-icons type="down" size="14" color="#666"></uni-icons>
			</view>
			<view class="filter-item">
				<text class="filter-text">默认排序</text>
				<uni-icons type="down" size="14" color="#666"></uni-icons>
			</view>
			<view class="filter-item">
				<text class="filter-text">美食分类</text>
				<uni-icons type="down" size="14" color="#666"></uni-icons>
			</view>
		</view>

		<!-- 错误提示 -->
		<view v-if="errorMsg" class="error-container">
			<uni-icons type="warn" size="20" color="#f53f3f" class="error-icon"></uni-icons>
			<text class="error-text">{{ errorMsg }}</text>
			<button class="retry-btn" @click="getStoreList">重新加载</button>
		</view>

		<!-- 商家列表 -->
		<view class="store-list" v-else>
			<view class="store-card" v-for="store in storeList" :key="store.storeId"
				@click="goToStoreDetail(store.storeId)">
				<view class="store-img-wrap">
					<image :src="handleImgURL(store.storeLogo)" mode="aspectFill" class="store-logo" lazy-load></image>
					<view class="store-tags" v-if="store.tags && store.tags.length">
						<text class="tag" v-for="(tag, idx) in store.tags" :key="idx"
							:style="{backgroundColor: tag.color || '#ff7a45'}">
							{{ tag.name }}
						</text>
					</view>
					<view class="storeStatus-badge" :class="store.storeStatus === 1 ? 'open' : 'close'">
						{{ store.storeStatus === 1 ? '营业中' : '休息中' }}
					</view>
				</view>
				<view class="store-info">
					<text class="store-name">{{ store.storeName }}</text>
					<view class="store-meta">
						<view class="rating-wrap" v-if="store.rating">
							<uni-icons type="star" size="14" color="#FFD166" class="star-icon"></uni-icons>
							<text class="rating-value">{{ store.rating.toFixed(1) }}</text>
						</view>
						<text class="distance" v-if="store.distance">{{ store.distance }}km</text>
					</view>
					<!-- 新增营业时间展示 -->
					<view class="business-hours" v-if="store.openingTime">
						<uni-icons type="clock" size="12" color="#718096" class="hour-icon"></uni-icons>
						<text class="hour-text">{{ formatopeningTime(store.openingTime) }}</text>
					</view>
					<view class="delivery-info">
						<text class="delivery-time" v-if="store.deliveryTime">{{ store.deliveryTime }}分钟</text>
						<text class="split"
							v-if="store.deliveryTime && (store.minOrderPrice || store.deliveryFee)">|</text>
						<text class="min-price" v-if="store.minOrderPrice">起送¥{{ store.minOrderPrice }}</text>
						<text class="split" v-if="store.minOrderPrice && store.deliveryFee">|</text>
						<text class="delivery-fee" v-if="store.deliveryFee">配送¥{{ store.deliveryFee }}</text>
					</view>
					<view class="discount-tags" v-if="store.discountTags && store.discountTags.length">
						<text class="discount-tag" v-for="(tag, idx) in store.discountTags" :key="idx">{{ tag }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 无数据状态 -->
		<view class="no-data" v-if="!loading && !errorMsg && storeList.length === 0">
			<uni-icons type="food" size="60" color="#ffe0d0"></uni-icons>
			<text class="no-data-text">暂无相关美食商家</text>
			<text class="no-data-subtext">换个关键词试试吧~</text>
		</view>
	</view>
</template>

<script>
	import {
		listStore
	} from '@/api/store.js'
	import {
		baseUrl
	} from '@/utils/config.js'

	export default {
		data() {
			return {
				storeList: [],
				loading: false,
				errorMsg: '',
				searchKey: '',
				// 分页参数
				pageNum: 1,
				pageSize: 10,
				hasMore: true,
				searchTimer: null // 防抖定时器
			}
		},
		onLoad() {
			this.getStoreList()
		},
		onReachBottom() {
			if (this.hasMore && !this.loading && !this.errorMsg) {
				this.pageNum++
				this.getStoreList()
			}
		},
		methods: {
			// 处理图片URL
			handleImgURL(url) {
				if (!url) return '/static/images/default-food.png'
				return url.includes('http') ? url : `${baseUrl}${url}`
			},

			// 格式化营业时间显示
			formatopeningTime(hours) {
				// 支持两种格式：字符串"09:00-22:00"或数组["09:00-14:00", "17:00-22:00"]
				if (Array.isArray(hours)) {
					return hours.join(' | ')
				}
				return hours || '营业时间待定'
			},

			// 检查是否在营业时间内（辅助方法）
			isInopeningTime(openingTime) {
				if (!openingTime) return false

				const now = new Date()
				const currentHour = now.getHours()
				const currentMinute = now.getMinutes()
				const currentTime = currentHour * 60 + currentMinute

				// 处理数组格式的营业时间
				const hoursList = Array.isArray(openingTime) ? openingTime : [openingTime]

				for (const time of hoursList) {
					const [startStr, endStr] = time.split('-')
					if (!startStr || !endStr) continue

					const [startHour, startMinute] = startStr.split(':').map(Number)
					const [endHour, endMinute] = endStr.split(':').map(Number)

					const startTime = startHour * 60 + startMinute
					const endTime = endHour * 60 + endMinute

					// 处理跨天情况（如22:00-02:00）
					if (startTime > endTime) {
						if (currentTime >= startTime || currentTime <= endTime) {
							return true
						}
					} else {
						if (currentTime >= startTime && currentTime <= endTime) {
							return true
						}
					}
				}
				return false
			},

			// 获取商家列表
			async getStoreList() {
				this.loading = true
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize,
						keyword: this.searchKey || undefined
					}

					const res = await listStore(params)
					if (![200, 0].includes(res.code) || !res.data) {
						throw new Error(res.msg || '获取商家失败')
					}

					// 格式化数据（包含营业时间处理）
					const formatData = res.data.map(store => ({
						...store,
						tags: store.tags || [],
						discountTags: store.discountTags || [],
						rating: store.rating !== undefined ? store.rating : (4.0 + Math.random() * 1.0),
						deliveryTime: store.deliveryTime !== undefined ? store.deliveryTime : Math.floor(
							Math.random() * 25) + 15,
						distance: store.distance !== undefined ? store.distance : (Math.random() * 3 + 0.3)
							.toFixed(1),
						minOrderPrice: store.minOrderPrice !== undefined ? store.minOrderPrice : Math
							.floor(Math.random() * 20) + 10,
						// 新增营业时间字段处理
						openingTime: store.openingTime || '营业时间待定',
						// 优化营业状态：如果接口没有返回状态，根据营业时间自动判断
						storeStatus: store.storeStatus !== undefined ? store.storeStatus : this
							.isInopeningTime(store.openingTime) ? 1 : 0
					}))

					this.storeList = this.pageNum === 1 ? formatData : [...this.storeList, ...formatData]
					this.hasMore = this.storeList.length < (res.total || 0)
				} catch (err) {
					this.errorMsg = err.message
					uni.showToast({
						title: err.message,
						icon: 'none',
						duration: 2000
					})
					if (this.pageNum === 1) this.storeList = []
				} finally {
					this.loading = false
				}
			},

			// 搜索防抖
			handleSearch() {
				clearTimeout(this.searchTimer)
				this.searchTimer = setTimeout(() => {
					this.pageNum = 1
					this.getStoreList()
				}, 500)
			},

			// 搜索确认
			handleSearchConfirm() {
				clearTimeout(this.searchTimer)
				this.pageNum = 1
				this.getStoreList()
			},

			// 清空搜索
			clearSearch() {
				this.searchKey = ''
				clearTimeout(this.searchTimer)
				this.pageNum = 1
				this.getStoreList()
			},

			goToStoreDetail(storeId) {
			  console.log('当前点击的店铺ID：', storeId) // 确认是第一家店的ID
			  uni.navigateTo({
			    url: `/pages/goods/storeDetail?storeId=${storeId}`
			  })
			}
		}
	}
</script>

<style scoped>
	/* 样式部分保持不变，此处省略 */
	.food-store-page {
		min-height: 100vh;
		background-color: #fff8f5;
	}

	.navbar {
		padding: 16px 16px 12px;
		background-color: #fff;
	}

	.title {
		font-size: 19px;
		font-weight: 700;
		color: #2d3748;
		display: block;
		margin-bottom: 12px;
	}

	.search-box {
		position: relative;
		height: 38px;
		background-color: #fff5f0;
		border-radius: 20px;
		padding: 0 16px;
		display: flex;
		align-items: center;
	}

	.search-input {
		flex: 1;
		height: 100%;
		background: transparent;
		font-size: 14px;
		color: #4a5568;
		padding-left: 6px;
	}

	.clear-icon {
		position: absolute;
		right: 16px;
		cursor: pointer;
	}

	.filter-bar {
		display: flex;
		background-color: #fff;
		padding: 12px 16px;
		border-bottom: 1px solid #fee9e1;
	}

	.filter-item {
		display: flex;
		align-items: center;
		margin-right: 28px;
	}

	.filter-text {
		font-size: 14px;
		color: #4a5568;
		margin-right: 4px;
	}

	.error-container {
		background-color: #fff5f5;
		border-radius: 10px;
		padding: 14px;
		margin: 12px;
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.error-icon {
		margin-top: 2px;
	}

	.error-text {
		color: #e53e3e;
		font-size: 14px;
		flex: 1;
	}

	.retry-btn {
		background-color: #ff7a45;
		color: #fff;
		padding: 6px 14px;
		border-radius: 6px;
		font-size: 14px;
		border: none;
	}

	.store-list {
		padding: 12px 16px;
	}

	.store-card {
		display: flex;
		background-color: #fff;
		border-radius: 12px;
		overflow: hidden;
		margin-bottom: 14px;
		box-shadow: 0 2px 8px rgba(255, 122, 69, 0.08);
		transition: all 0.2s ease;
	}

	.store-card:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(255, 122, 69, 0.12);
	}

	.store-img-wrap {
		width: 110px;
		height: 110px;
		flex-shrink: 0;
		position: relative;
	}

	.store-logo {
		width: 100%;
		height: 100%;
		object-fit: cover;
		border-radius: 12px 0 0 12px;
	}

	.store-tags {
		position: absolute;
		top: 8px;
		left: 8px;
		display: flex;
		gap: 6px;
		z-index: 1;
	}

	.tag {
		font-size: 11px;
		color: #fff;
		padding: 2px 6px;
		border-radius: 4px;
		text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
		white-space: nowrap;
	}

	.storeStatus-badge {
		position: absolute;
		top: 8px;
		right: 8px;
		font-size: 11px;
		padding: 2px 6px;
		border-radius: 4px;
		color: #fff;
	}

	.storeStatus-badge.open {
		background-color: rgba(0, 180, 42, 0.8);
	}

	.storeStatus-badge.close {
		background-color: rgba(153, 153, 153, 0.8);
	}

	.store-info {
		flex: 1;
		padding: 14px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.store-name {
		font-size: 16px;
		font-weight: 600;
		color: #2d3748;
		line-height: 1.3;
		margin-bottom: 4px;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.store-meta {
		display: flex;
		align-items: center;
		gap: 12px;
		margin-bottom: 6px;
	}

	.rating-wrap {
		display: flex;
		align-items: center;
		gap: 3px;
	}

	.rating-value {
		font-size: 13px;
		color: #dd6b20;
		font-weight: 500;
	}

	.distance {
		font-size: 12px;
		color: #718096;
		margin-left: auto;
	}

	/* 新增营业时间样式 */
	.business-hours {
		display: flex;
		align-items: center;
		gap: 4px;
		margin-bottom: 6px;
	}

	.hour-text {
		font-size: 12px;
		color: #718096;
	}

	.delivery-info {
		display: flex;
		align-items: center;
		gap: 8px;
		margin-bottom: 6px;
	}

	.delivery-time {
		font-size: 12px;
		color: #4a5568;
	}

	.min-price {
		font-size: 12px;
		color: #4a5568;
	}

	.delivery-fee {
		font-size: 12px;
		color: #4a5568;
	}

	.split {
		color: #e2e8f0;
		font-size: 12px;
	}

	.discount-tags {
		display: flex;
		gap: 6px;
		flex-wrap: wrap;
	}

	.discount-tag {
		font-size: 11px;
		color: #dd6b20;
		border: 1px solid #fed7d7;
		padding: 1px 5px;
		border-radius: 3px;
		background-color: #fff5f0;
	}

	.no-data {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60px 0 40px;
	}

	.no-data-text {
		color: #a0aec0;
		font-size: 15px;
		margin-top: 16px;
	}

	.no-data-subtext {
		color: #cbd5e0;
		font-size: 13px;
		margin-top: 8px;
	}

	button {
		line-height: normal;
	}

	button::after {
		border: none;
	}
</style>